﻿using System;
using System.Collections.Generic;
using RedBit.OAuthLibrary;

namespace TradeMeSDK.OAuthLibrary
{
    public static class TradeMeOAuth
    {
        public static string RequestTokenUrl = "https://secure.trademe.co.nz/Oauth/RequestToken";
        public static string Authorize { get { return "https://secure.trademe.co.nz/Oauth/Authorize?oauth_token=" + Token; } }
        public static string AuthenticationUrl { get { return string.Format("https://secure.trademe.co.nz/Oauth/Authorize?oauth_token={0}", Token); } }
        public static string AccessTokenUrl { get { return string.Format("https://secure.trademe.co.nz/Oauth/AccessToken?oauth_verifier={0}", Verifier); } }

        //key and secret when app is registered
        public static string ConsumerKey;
        public static string ConsumerSecret;

        //received after the token has been requested
        public static string Token { get; set; }
        public static string TokenSecret { get; set; }

        // Received after the user has logged in
        public static string Verifier { get; set; }

        //these valuse are set once the OAuth process is complete
        public static string UserId { get; set; }
        public static string ScreenName { get; set; }

        [Flags]
        public enum TradeMeScope
        {
            Read = 0x00,
            Write = 0x01,
            BiddingAndBuying = 0x02,
            All = 0x03
        }
        public static TradeMeScope Scope;

        public static string RequestToken
        {
            get
            {
                if (Scope == TradeMeScope.Read)
                    return RequestTokenUrl;
                string url = RequestTokenUrl + "?scope=MyTradeMeRead";
                if ((Scope & TradeMeScope.Write) == TradeMeScope.Write)
                    url += ",MyTradeMeWrite";
                if ((Scope & TradeMeScope.BiddingAndBuying) == TradeMeScope.BiddingAndBuying)
                    url += ",BiddingAndBuying";
                return url;
            }
        }

        private static EventHandler _accessTokenCallBack;
        public static void BeginGetToken(EventHandler callBack)
        {
            _accessTokenCallBack = callBack;

            RedBit.OAuthLibrary.OAuth.GetAccessToken(
                    AccessTokenUrl, ConsumerKey, ConsumerSecret, Token, TokenSecret, 
                    EndGetToken);
        }

        public static void EndGetToken(object sender, OAuthEventArgs args)
        {
            if (args.IsError)
                throw new Exception(args.Error.Message, args.Error);

            Dictionary<string, string> result = Helpers.ParseQueryString(args.Response);
            Token = result["oauth_token"];
            TokenSecret = result["oauth_token_secret"];

            _accessTokenCallBack(null, new EventArgs());
        }

    }
}
